package com.example.controller;

import com.example.dao.impl.UserDaoimpl;
import com.example.utils.DButil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        UserDaoimpl userDaoimpl = new UserDaoimpl();
        int touserid = userDaoimpl.findByUsername(username).getUserId();

        HttpSession session = req.getSession();
        session.setAttribute("touserid", touserid);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sql = "INSERT INTO liaotian (USERID1, USERID2,CONTENT) VALUES (?,?,?)";
        Connection con = DButil.getConnection();
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1, req.getParameter("right"));
            ps.setString(2, req.getParameter("left"));
            ps.setString(3, req.getParameter("text"));
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DButil.closeResources(con,ps);
        }


    }
}
